var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
var mongoose = require('mongoose');
var Goods = require('../models/goods.js');
var Users = require('../models/users.js');
var formidable = require('formidable');
var path = require('path');
var fs = require('fs');
require('../util/util.js');

app.use(bodyParser.urlencoded({ extended: false }))

mongoose.connect('mongodb://127.0.0.1:27017/dumall');

mongoose.connection.on("connected", function () {
	console.log("MongoDB connected success")
})
mongoose.connection.on("error", function () {
	console.log("MongoDB connected fail")
})
mongoose.connection.on("disconnected", function () {
	console.log("MongoDB connected disconnected")
})

// 查询商品列表
router.get("/list", function (req, res, next) {
	var pageNo = parseInt(req.query.pageNo) || 1;
	var pageSize = parseInt(req.query.pageSize) || 10;
	var sort = req.query.sort || 1;            // 默认正序
	var priceLevel = req.query.priceLevel;
	var params = {}
	var priceGt = '';
	var priceLte = '';
	var priceList = [
		{ priceGt: 0, priceLte: 100 },
		{ priceGt: 100, priceLte: 500 },
		{ priceGt: 500, priceLte: 1000 },
		{ priceGt: 1000, priceLte: 2000 },
		{ priceGt: 2000, priceLte: '' }
	]
	if (priceLevel !== 'all') {
		for (var i = 0; i < priceList.length; i++) {
			if (i === parseInt(priceLevel)) {
				priceGt = priceList[i].priceGt
				priceLte = priceList[i].priceLte
			}
		}
		if (parseInt(priceLevel) !== 4) {
			params = {
				salePrice: {
					$gt: priceGt,
					$lte: priceLte
				}
			}
		} else {
			params = {
				salePrice: {
					$gt: priceGt
				}
			}
		}
	}
	var skip = (pageNo - 1) * pageSize;
	var goodsModel = Goods.find(params).skip(skip).limit(pageSize);
	goodsModel.sort({'salePrice': sort});
	goodsModel.exec(function (err, doc) {
		if (err) {
			res.json({
				status: 1,
				msg: err.message
			})
		} else {
			res.json({
				status: 0,
				msg: '',
				result: {
					count: doc.length,
					list: doc
				}
			})
		}
	})
})

// 加入到购物车
router.post("/addCart", function (req, res, next) {
	var productId = Number(req.body.productId);
	Users.findOne({userId: 111}, function (err, userDoc) {
		if (err) {
			res.json({
				status: 1,
				msg: err.message
			})
		} else {
			if (userDoc) {
				let goodsItem = '';
				userDoc.cartList.forEach(function (item) {
					if (item.productId == productId) {
						goodsItem = item;
						item.productNum = parseInt(item.productNum) + 1
					}
				})
				if (goodsItem) {
					userDoc.save(function (err2, doc2) {
						if (err2) {
							res.json({
								status: 1,
								msg: err2.message
							})
						} else {
							res.json({
								status: 0,
								msg: ''
							})
						}
					})
				} else {
					Goods.findOne({productId: productId}, function (err1, goodDoc) {
						if (err1) {
							res.json({
								status: 1,
								msg: err1.message
							})
						} else {
							if (goodDoc) {
								// 这里不能使用es6的语法。也不能直接给goodDoc添加属性
								var good = {
								  productNum: 1,
    							  checked: "1",
								  productId: goodDoc.productId,
								  productName: goodDoc.productName,
								  salePrice: goodDoc.salePrice,
								  productImage: goodDoc.productImage
    							}
								userDoc.cartList.push(good);
								userDoc.save(function (err2, doc2) {
									if (err2) {
										res.json({
											status: 1,
											msg: err2.message
										})
									} else {
										res.json({
											status: 0,
											msg: ''
										})
									}
								})
							}
						}
					})
				}
			} else {
				res.json({
					status: 1,
					msg: '没找到该用户'
				})
			}
		}
	})
})
// 添加商品
router.post("/addGoods", function (req, res, next) {
	var productName = req.body.productName;
	var salePrice = Number(req.body.salePrice);
	var productImage = req.body.productImage;
	
	Goods.find({}, function (err, doc) {
		if (err) {
			res.json({
				status: 1,
				msg: err.message
			})
		} else {
			var newProductId = 0
			if (!doc || doc.length === 0) {
				newProductId = 1
			} else {
				newProductId = Number(doc[doc.length - 1].productId) + 1
			}
			var obj = {
				productId: newProductId,
				productName: productName,
				salePrice: salePrice,
				productImage: productImage
			}
			var monInsert = new Goods(obj);
			monInsert.save(function(err){
			 	if(err){
			 		res.json({
						status: 1,
						msg: err.message
					})
			 	}else{
			 		res.json({
						status: 0,
						msg: ''
					})
			 	}
			});
		}
	})
})
// 上传图片
router.post("/upload", function (req, res, next) {
	var form = new formidable.IncomingForm();
    form.uploadDir = path.normalize(__dirname + "/../tempup/");
    form.parse(req, function(err, fields, files, next) {
        //改名
        if(err){
            next();     //这个中间件不受理这个请求了，往下走
            return;
        }
        //判断文件尺寸
        var size = parseInt(files.productImage.size);
        if(size > 1024 * 1000 * 10){
            res.send("图片尺寸应该小于10M");
            //删除图片
            fs.unlink(files.productImage.path);
            return;
        }

        var ttt = new Date().Format('yyyyMMddhhmmss');
        var ran = parseInt(Math.random() * 89999 + 10000);
        var extname = path.extname(files.productImage.name);
        
        var oldpath = files.productImage.path;
        var newpath = path.normalize(__dirname + "/../public/" + ttt + ran + extname);
        fs.rename(oldpath,newpath,function(err){
            if(err){
                res.json({
                	status: 1,
                	msg: '改名失败'
                });
                return;
            }
            res.json({
            	status: 0,
            	msg: '成功',
            	result: 'http://localhost:3000/' + ttt + ran + extname
            });
        });
    });
})

module.exports = router;